import { enumStrokeColor, userPath, groupPath, rectNodeConfig } from '../theme'

const getUserModel = RectNodeModel => {
  class UserModel extends RectNodeModel {
    static extendKey = 'UserModel'
    constructor(data, graphModel) {
      const { text } = data
      if (text && typeof text === 'string') {
        const len = text.length - 1
        const count = Math.ceil((rectNodeConfig.width - 30) / 13)
        data.text = text.replace(
          /./g,
          (m, index) => m + (index % count === count - 1 && index !== len ? '\n' : '')
        )
      }
      super(data, graphModel)
    }
  }
  return UserModel
}

const getUserNode = (RectNode, h) => {
  class UserNode extends RectNode {
    static extendKey = 'UserNode'
    getShape() {
      const attributes = super.getAttributes()
      const { x, y, width, height, fill, stroke, strokeWidth, radius, properties = {} } = attributes
      const pStroke = enumStrokeColor[properties.type] || stroke
      const { viewBox, d } = properties.icon === 'group' ? groupPath : userPath
      return h('g', {}, [
        h('rect', {
          x: x - width / 2,
          y: y - height / 2,
          rx: radius,
          ry: radius,
          fill,
          stroke: pStroke,
          strokeWidth,
          width,
          height,
        }),
        h(
          'svg',
          {
            x: x - width / 2 + 2,
            y: y - height / 2 + 2,
            width: 22,
            height: 22,
            viewBox: `0 0 ${viewBox.w} ${viewBox.h}`,
          },
          d.map(it => h('path', { fill: pStroke, d: it }))
        ),
      ])
    }
  }
  return UserNode
}

export const registerUserNode = ({ RectNode, RectNodeModel, h }) => ({
  model: getUserModel(RectNodeModel),
  view: getUserNode(RectNode, h),
})
